<%@page import="Logic.CommitteeModify_BLL"%>
<%@page import="Logic.Authorizer"%>
<%@page import="servlet.StaffappStaffDropdown"%>
<%@page import="servlet.CommitteeRolesDropdown"%>
<%@page import="Model.Committee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="Database.CommitteeRoleDB"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%
	if (session.getAttribute("name") == null) {
		response.sendRedirect("login.jsp");
	} else {
		if (Authorizer.checkRole("1", session.getAttribute("role")
				.toString()) || Authorizer.checkRole("3", session.getAttribute("role").toString())) {
			
		}
		else
		{
			response.sendRedirect("nopermission.jsp");
						
		}
	}
%>


<!-- Declare the first header -->
<jsp:include page="t_header.jsp" />

<!-- Javascript -->
<link rel="stylesheet" type="text/css"
	href="css/smoothness/jquery-ui-1.9.1.custom.min.css" />
	
<script type="text/javascript" src="js/jquery-ui-1.9.0.custom.min.js"></script>
<link rel="stylesheet" href="css/jquery.ui.all.css" />
<script src="js/jquery-ui-1.10.0.custom.js"></script>
<script type="text/javascript">
	var rowindex = 0;
	
	function checkifsingleempty(){
		var numfield = 0;
		var emptyone = false;
		for( var a = 0; a <= rowindex; a ++ )
		{
			
			var checkrole = document.getElementById("role" + a).value;
			var checkstaff = document.getElementById("staff" + a).value;
			if(checkrole != null && checkstaff != null )
			{
			
				numfield ++ ;
				
					if(checkrole == "" && checkstaff == "" )
					{
						emptyone = true;
					}
					
			}
			
		 }
		
		if(emptyone == true && numfield == 1){
			//confirm
			return confirm("Are you sure you don't want roles in this Committee ?");
			
		}
		else{
		return true;
		}
	}
	
	function add(id) {
		var number = id.charAt(id.length - 1);

		var e = document.getElementById("selectstaff" + number);
		var name = e.options[e.selectedIndex].value;

		var staff = document.getElementById("staffnames" + number).value;

		var array = [];
		var staffs = document.getElementsByTagName("textarea");
		var arr = [];

		for ( var x = 0; x < staffs.length; x++) {
			var value = staffs.item(x).value;
			if (value != "") {
				array = value.split(', ');
				arr = arr.concat(array);
			}
		}

		if (jQuery.inArray(name, arr) == -1) {
			if (staff == "") {
				document.getElementById("staffnames" + number).value = staff
						.concat(name);
			} else {
				staff = staff.concat(', ');
				document.getElementById("staffnames" + number).value = staff
						.concat(name);
			}
		}
	}

	function remove(id) {
		var number = id.charAt(id.length - 1);

		var staff = document.getElementById("staffnames" + number).value;

		var array = staff.split(',');

		if (staff != "") {
			array.pop();
			document.getElementById("staffnames" + number).value = array;
		}
	}

	function removeRowFromTable() {
		var table = document.getElementById("myTable");
		var rowCount = table.rows.length;
		var numofrow = table.rows.length - 1;
// 		if (rowCount > 2) {
// 			table.deleteRow(-1);
// 			document.getElementById("numberOfRow").value = rowCount - 2;
// 		}
		var lastRow = rowCount - 2;
		
		if(rowindex == 0)
		{

		rowindex = table.rows.length - 2;

		}
		
		
		for( var a = 0; a <= rowindex; a ++ )
		{
			
			var checkrow = document.getElementById("check" + a);
			if(checkrow == null)
			{
				
			}
			else{
				lastRow = a;
				

			}
				
		 }

		
		//an array here of all checked values
	var checksel;
	var tempRow = 1;
for( var i=0; i <= lastRow; i ++ )
{
	checksel = document.getElementById("check"+i);
	if(checksel != null){
		
	
	    if( checksel.checked == true)
		{
	    	
	    	if( tempRow != numofrow)
	    		{
	    		//delete
				var b = document.getElementById("tbody");
				var d = document.getElementById("tr" + i);
			
				b.removeChild(d);
				
				
				
				
				
				tempRow ++ ;
	    		}
	    	else{
	    		addRowToTable();
	    		//delete
				var b = document.getElementById("tbody");
				var d = document.getElementById("tr" + i);
			
				b.removeChild(d);
				
	    		
	    		}
	    	
		
			
		}
	}
	    
}



if (tempRow != 1){
	
	//remove breaks
	var additionalbreaks2 = document.getElementById("additionalbreaks");
	tempRow = tempRow - 1;
	var stopbreakdel = 1;
		for( var c = 0 ; c <= rowindex ; c ++)
			{
			if( stopbreakdel <= tempRow)
				{
				var main2 = document.getElementById("breaker" + c);
				if( main2 != null){
					
					additionalbreaks.removeChild(main2);
					stopbreakdel ++;
								  }
				}
			
			
			}

				}	




var rowCount2 = table.rows.length;
document.getElementById("numberOfRow").value = rowCount2 - 1;
	}

	function addRowToTable() {
		var table = document.getElementById("myTable");

		var rowCount = table.rows.length;
		var lastRow = rowCount - 2;
		var newRow = rowCount - 1;
		var row = table.insertRow(rowCount);

		if(rowindex == 0)
		{

		rowindex = table.rows.length - 2;

		}
		
		
		for( var a = 0; a <= rowindex; a ++ )
		{
			
			var checkrow = document.getElementById("check" + a);
			if(checkrow == null)
			{
				
			}
			else{
				lastRow = a;
				newRow = a + 1 ;
				

			}
				
		 }
	
		

		
		var cell0 = row.insertCell(0);
		var clncheck = document.getElementById("check" + lastRow).cloneNode(true);
		clncheck.id = "check" + newRow;
		clncheck.checked = false;
		cell0.appendChild(clncheck);
		
		
		var cell1 = row.insertCell(1);
		var idele = "role" + lastRow;
		var cln = document.getElementById(idele);
		var roleText = cln.cloneNode(true);
		roleText.id = "role" + newRow;
		roleText.name = "role" + newRow;
		roleText.value = "";
		cell1.appendChild(roleText);
		cell1.valign = top;
		
		row.id= "tr" + newRow;
		
		var cell2 = row.insertCell(2);

		var staffnames = document.getElementById("staffnames"  + lastRow).cloneNode(true);
		staffnames.id = "staffnames" + newRow;
		
		staffnames.innerHTML = "";
		cell2.appendChild(staffnames);
		
		
		var selectstaff = document.getElementById("selectstaff"  + lastRow).cloneNode(true);
		selectstaff.id = "selectstaff" + newRow;
		cell2.appendChild(selectstaff);
		

		

		var add = document.getElementById("add"+ lastRow).cloneNode(true);
		add.id = "add" + newRow;
		add.onclick = function newroleaddStaff(){
			addStaff(newRow);
		};
		
		
		var rem = document.getElementById("rem"+ lastRow).cloneNode(true);
		rem.id = "rem" + newRow;
		rem.onclick = function newroleremoveStaff(){
			removeStaff(newRow);
		};
		
		var div1 = document.getElementById("div"+ lastRow).cloneNode(true);
		div1.id = "div" + newRow;
		div1.innerHTML = "";
		
		div1.appendChild(add);
		div1.appendChild(rem);
		
		cell2.appendChild(div1);

		var staff = document.getElementById("staff"+ lastRow).cloneNode(true);
		staff.id = "staff" + newRow;
		staff.name = "staff" + newRow;
		staff.value = "";
		cell2.appendChild(staff);
		
		
		
		var additionalbreaks = document.getElementById("additionalbreaks");
		var main = document.getElementById("breaker").cloneNode(true);
		main.id = "breaker" + rowindex;
		main.style.display = "block";
		additionalbreaks.appendChild(main);
		
		document.getElementById("rowindex").value = rowindex;
		
		if(rowindex == 0)
			{

			rowindex = table.rows.length - 2;
	
			}
		else{
			rowindex= rowindex + 1;

		}
		
		document.getElementById("numberOfRow").value = rowCount;
		
	}
	

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




function addStaff(i) {
var stafflist = document.getElementById("staffnames" + i);

var e = document.getElementById("selectstaff" + i);

var name = e.options[e.selectedIndex].text;

var id = e.options[e.selectedIndex].value;
if(isOptionAlreadyExist(stafflist,id)){
alert('Staff already added');
return false;
}

var staff = document.getElementById("staff" + i).value;

var array = staff.split(', ');

if (staff == "") {
document.getElementById("staff" + i).value = id;
} else {
if (jQuery.inArray(name, array) == -1) {
staff = staff.concat(', ');
document.getElementById("staff" + i).value = staff
.concat(id);
}
}

var optn = document.createElement("option");

optn.text = name;

optn.value = id;

stafflist.add(optn,null);

}

function isOptionAlreadyExist(listBox,value){
var exists=false;

for(var x=0; x<listBox.options.length; x++){

if(listBox.options[x].value==value || listBox.options[x].text==value){ 

exists=true;

break;
}
}
return exists;
}

function removeStaff(i) {
var stafflist = document.getElementById("staffnames" + i);

var optionToRemove =stafflist.options.selectedIndex;

stafflist.remove(optionToRemove);

var tempStaff = "";

for(var x=0;x<stafflist.options.length;x++){
if (tempStaff == "") {
tempStaff = stafflist.options[x].value;
} else {
tempStaff = tempStaff.concat(', ');
tempStaff = tempStaff.concat(stafflist.options[x].value);
}
}

document.getElementById("staff" + i).value = tempStaff;



return true;
}

function addAppointment() {

var e = document.getElementById("appointment");
var name = e.options[e.selectedIndex].value;
var staff = document.getElementById("appointmentnames").value;

var array = staff.split(', ');

if (staff == "") {
document.getElementById("appointmentnames").value = name;
} else {
if (jQuery.inArray(name, array) == -1) {
staff = staff.concat(', ');
document.getElementById("appointmentnames").value = staff
.concat(name);
}
}

}

function removeAppointment() {
var staff = document.getElementById("appointmentnames").value;

var array = staff.split(',');

if (staff != "") {
array.pop();
document.getElementById("appointmentnames").value = array;
}
}

function reload (list) {

var staffid1 = $("#staffnames").val();
//var list = document.getElementById("selectstaff");
//var staffid1 = list.options[list.selectedIndex].value;
//alert(staffid1);
var appointmentid1 = $("#appointment").val();
$.ajax({
url: 'StaffappStaffSidebox',
data: {staffid :staffid1, appointmentid : appointmentid1},
type: 'get',
success: function(msg){
document.getElementById('staffdetails').style.display = 'block';
$("#staffdetails").html(msg);
}
});

};

function reload1 (list) {

var staffid1 = $("#selectstaff" + i).val();
var appointmentid1 = $("#appointment").val();
$.ajax({
url: 'StaffappStaffSidebox',
data: {staffid :staffid1, appointmentid : appointmentid1},
type: 'get',
success: function(msg){
document.getElementById('staffdetails').style.display = 'block';
$("#staffdetails").html(msg);
}
});

};

$(document).ready(function() {
//confirmation dialog defination
$("#dialog-confirm").dialog({
autoOpen : false,
show: {
effect:"drop",
duration: 1000
},
hide: {
effect:"drop",
duration: 1000
},
resizable : false,
modal : true,
buttons : {
"Confirm Appointment" : function() {
$("#newApp").submit();
},
Cancel : function() {
$(this).dialog("close");
}
},
open : {

},
close : function(event, ui) {
//Cleaup routine to reset the data for the next time the form opens

}
});

//onclick appointstaff button
$("#testdialog").click(function() {



//get effective date
var effdate = document.getElementById("inputField").value;

//get all names in listbox
var list = $.trim(document.getElementById("staffnames").innerHTML);


if( !effdate || list == "" || !list || list == null ){

$("#newApp").submit();
}
else{

list = document.getElementById("staffnames");
var arr = $.map(list.options, function(o){
return o.text;
});
var test = arr.join(', ');

//get appointment from dropdownlist
var appt = $("#appointment option:selected").text();

//set content
document.getElementById("dialogmsg").innerText = "Appoint " + test + " as " + appt + "?";

//display dialog box
$("#dialog-confirm").dialog("open");
}
});
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

</script>

<!-- Declare Breadcrumbs options -->

<jsp:include page="header.html" />
<!-- Declare sidebar -->
<jsp:include page="t_siderbarcommittee.jsp" />

<!-- Main Content -->
<section id="main" class="column">
	<%
		if (request.getParameter("error") != null) {
			if (request.getParameter("error").equals("1"))
				out.print("<h4 class='alert_error'>Error - Please fill in all fields.</h4>");
			else if (request.getParameter("error").equals("2"))
				out.print("<h4 class='alert_error'>Error - Role Name cannot be the same.</h4>");
			else if (request.getParameter("error").equals("-1"))
				out.print("<h4 class='alert_success'>Staffs appointed to committee successfully.</h4>");
			else if (request.getParameter("error").equals("-2"))
				out.print("<h4 class='alert_success'>The committee, " + request.getAttribute("title").toString().trim() + ", has been created successfully.</h4>");
		
		}
	%>
	<%
		Committee comm = new Committee();
		if (request.getParameter("id") != null) {
			try {
				comm = CommitteeModify_BLL.getNewCommitteebyID(request
						.getParameter("id"));
			} catch (Exception e) {
				System.out.println(e);
			}
		}
	%>
	<%
		if (request.getParameter("action") != null) {
			if (request.getParameter("action").equals("d"))
				out.print("<h4 class='alert_warning'>Please confirm your deletion of &quot;"
						+ comm.getTitle() + "&quot;.</h4>");
			else if (request.getParameter("action").equals("e"))
				out.print("<h4 class='alert_info'>You are now editing &quot;"
						+ comm.getTitle() + "&quot;.</h4>");
		}
	%>

	<div class="clear"></div>

	<%
		if (request.getParameter("action") != null
				&& request.getParameter("action").equals("e")
				&& request.getParameter("id") != null) {
	%>

	<article class="module width_3_quarter">
		<form action="EditCommittee2" method="POST" id="form">
			<header>
				<h3>Add staff to committee</h3>

			</header>
			<table id="myTable" class="tablesorter" cellspacing="0">
				<thead>
					<tr>
						<th> </th>
						<th>Role Name</th>
						<th>Staff</th>
					</tr>
				</thead>
				<tbody  id="tbody" valign="top">
					<%
					int lasti = 0;
						String x = request.getAttribute("commListRow").toString();
							if (!x.equals("0")) {
								int rows = Integer.parseInt(x);
								for (int i = 0; i < rows; i++) {
					%>
					<tr id="tr<%=i%>">
					<td>
					<!-- multiple select -->
					<input type="checkbox" id="check<%=i%>" name="check" value="" >
					
					</td>
						<td><input type="text" id="role<%=i%>" name="role<%=i%>"
							value="<%=request.getAttribute("roleName" + i)
								.toString()%>"
							size="35"></td>
							
							
						<td>
						
						<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->			

				
					<!-- List Box for putting multiple staffs -->
					<select id="staffnames<%=i %>" name="staffnames" class="change" onchange="reload(this)" size="5"
						style="width: 60%; height: 10%; margin-bottom: 2%"><%

						if(request.getAttribute("staffName" + i) != null && request.getAttribute("staffnamelist" + i) != null )
						{								
						//seperate staff  by , into an array
						String staff2 = (String) request.getAttribute("staffName" + i);
						String[] stafflist2 = staff2.split(", ");
						ArrayList<String> staffnamelist ;
						staffnamelist = (ArrayList<String>) request.getAttribute("staffnamelist" + i);  //request.getAttribute("staffnamelist");
						String staff;
						
						//send staff login id and return name and store in array
						for (int a = 0; a < stafflist2.length;  a++) {
							
							staff = staffnamelist.get(a);
							out.println("<OPTION value="+ stafflist2[a] +" >"+ staff  +"</OPTION>");
						}
						
								 }%></select>
					
					<!-- Drop down list to select staff appointment -->
					<select id="selectstaff<%=i %>" class="change" onchange="reload1(this)">
						<%
							StaffappStaffDropdown ssd = new StaffappStaffDropdown(out);
								ssd.doGet(request, response);
						%>
					</select>

					<!-- two buttons for adding and removing staff name from textarea -->
					<div id="div<%=i %>"  style="margin-left: 4%; margin-top: 2%">
						<button style="margin-left:-10px;" type="button" id="add<%=i %>" onclick="addStaff(<%out.print(i);%>)">Add</button>
						<button type="button" id="rem<%=i %>" onclick="removeStaff(<%out.print(i);%>)">Remove</button>
					</div>
		
				

					<input type="hidden"  name="staff<%=i %>"  id="staff<%=i %>"
					value="<%
					if(!request.getAttribute("staffName" + i) .equals(""))
					{
							String staff3 = (String) request.getAttribute("staffName" + i).toString();
					
					out.print(staff3);
					}
					%>" />
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
	
						
						
						
					</td>
					</tr>
					<%
					

			
						}
							
							
							} else {
	
					%>
					<tr id="tr0">
					<%lasti = lasti + 1;%>
					<td>
					<!-- multiple select -->
					<input type="checkbox" id="check0" name="check" value="" >
					
					</td>
						<td><input type="text" id="role0" name="role0" value=""
							size="35"></td>
						<td>
						
								<!-- List Box for putting multiple staffs -->
					<select id="staffnames0" name="staffnames" class="change" onchange="reload(this)" size="5"
						style="width: 60%; height: 10%; margin-bottom: 2%"><%

						%></select>
					
					<!-- Drop down list to select staff appointment -->
					<select id="selectstaff0" class="change" onchange="reload1(this)">
						<%
							StaffappStaffDropdown ssd = new StaffappStaffDropdown(out);
								ssd.doGet(request, response);
						%>
					</select>

					<!-- two buttons for adding and removing staff name from textarea -->
					<div  id="div0" style="margin-left: 4%; margin-top: 2%">
						<button style="margin-left:-10px;" type="button" id="add0" onclick="addStaff(0)">Add</button>
						<button type="button" id="rem0" onclick="removeStaff(0)">Remove</button>
					</div>
		
				

					<input type="hidden" name="staff0"  id="staff0"
					value="<%
					
					%>" />
					<% x = "1"; %>
							</td>
							
					</tr>
					<%
						}
					%>
				</tbody>
			</table>
			<% request.setAttribute("rowindex", Integer.parseInt(x) - 1); %>
			<input type="hidden" id="rowindex" name="rowindex" value="<% 
			
					if(request.getAttribute("rowindex") == null )
					{
						out.println(request.getAttribute("rowindex"));
					}else{
						int tempri = Integer.parseInt(x) - 1;
						out.println(tempri);
			}%>">
			<input  type="hidden"  id="numberOfRow" name="numberOfRow" value="<%=
			
				Integer.parseInt(x)
				
				%>" >
			<input type="hidden" value=<%=comm.getId()%> name="committeeId">
			<footer>
				<input type="button" onclick="addRowToTable()" value="Add role">
				<input type="button" onclick="removeRowFromTable()"
					value="Remove role">
				<div class="submit_link">
					<input name="submit" type="submit" value="Cancel" class="alt_btn">
					<input name="submit" type="submit" value="Save" onclick="return checkifsingleempty();" class="alt_btn">
				</div>
			</footer>
		</form>
		
	</article>
	<%
		}
	%>
	<!-- end of post new article -->
	<div class="spacer"></div>
	
</section>
<section id="additionalbreaks">
<div id="breaker" style="display:none;">
<div style="background:White; padding-bottom: 171px; " >&nbsp;</div> 
</div>
</section>


<!-- Declare closing tags -->
<jsp:include page="t_footer.jsp" />